//
//  BSDataBaseManager.m
//  BS
//
//  Created by lanou on 15/8/19.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "BSDataBaseManager.h"

#import "FMDB.h"

@interface BSDataBaseManager ()



@end

@implementation BSDataBaseManager

+ (BSDataBaseManager *)defaultManager{

    static BSDataBaseManager *manager = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (instancetype)init{

    if (self = [super init]) {
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"BSDataBase"];
//          NSLog(@"%@",path);
        _db = [FMDatabase databaseWithPath:path];
        [_db open];
        [_db executeUpdate:@"CREATE TABLE list(Name text primary key,Data blob)"];
        [_db executeUpdate:@"CREATE TABLE newlist(Name text primary key,Data blob)"];
    }
  
    return self;
}

- (void)addDataName:(NSString *)name data:(NSData *)data withTableName:(NSString *)tableName{

    NSString *sqlStr = [NSString stringWithFormat:@"INSERT INTO %@ (Name, Data) VALUES (?, ?)",tableName];
    NSLog(@"插入%@:%d",name,[_db executeUpdate:sqlStr,name,data]);
}

- (NSData *)dataWithName:(NSString *)name withTableName:(NSString *)tableName{

    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE Name = ? ",tableName];
    NSData *data = nil;
    FMResultSet *result = [_db executeQuery:sqlStr,name];
    while ([result next]) {
        data = [result dataForColumn:@"Data"];
    }
    [result close];
    return data;
}

- (void)setData:(NSData *)data name:(NSString *)name withTableName:(NSString *)tableName{

    NSString *sqlStr = [NSString stringWithFormat:@"UPDATE %@ SET Data = ? WHERE Name = ? ",tableName];
    [_db executeUpdate:sqlStr,data,name];
}
@end
